import os
from models import Application, Model

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.conf import settings

def create_table(sql):
    from django.db import connection
    cursor = connection.cursor()
    try:
        cursor.execute(sql)
    except Exception, e:
        raise Exception, e

@staff_member_required
def select_for_models(request, id="0"):
    select = [u"<Select name='@name@' id='@id@'>"]
    models = Model.objects.all()
    select.append("<option value=''>---------</option>")
    for model in models:
        selected=""
        if int(id) == model.id: 
            selected = "selected"
        select.append("<option value='%s' %s>%s.%s</option>" % (model.id, selected, model.application, model))
    select.append("</select>")
    return HttpResponse("\n".join(select))

@staff_member_required
def run_syncdb(request):
    directory = "%s/" % (settings.PROJECT_DIR)
    all_apps = Application.objects.all()

    for app in all_apps:
        if not app.is_installed:
            #app.is_installed = True
            app.save()
            settings_path_file = "%ssettings.py" % (directory)
            f = open(settings_path_file, 'r')
            new_settings = ""
            for line in f.readlines():
                new_settings += line
                if "MagicAdmin" in line:
                    new_settings += line.replace("MagicAdmin", app.name)
            f.close()
            f = open(settings_path_file, 'w')
            f.write(new_settings)
            f.close()

            command = "python %smanage.py sql %s" % (directory, app.name)
            sql = "".join(os.popen(command).readlines())
            try:
                create_table(sql)
                messages.add_message(request, messages.INFO, "%s created." % app.name)
                models = Model.objects.filter(application=app)
                admin = "from %s.models import *\n" % (app.name, )
                admin += "from django.contrib import admin\n\n"
                for model in models:
                    admin += "admin.site.register(%s)\n" % (model.name,)
                open("%s%s/admin.py" % (directory, app.name,), "w").write(admin)
            except Exception, e:
                messages.add_message(request, messages.ERROR, "%s\n\n\n%s" % (sql, e))
        else:
            # TODO: Here we have to update the definitions.
            pass

    return HttpResponseRedirect('/admin')
    

